package corp.sunny.commons.util.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.log4j.Logger;

/**
 * @File:JAASCallbackHandler.java
 * @Date:Jun 9, 2011
 * @Author:Subhash Bavi
 * 
 * @Description: JAAS Custom Callback Handler
 * @Copyright Sunny Corporation - 2011
 */
public class JAASCallbackHandler implements CallbackHandler {

	private final Logger LOG = Logger.getLogger(JAASCallbackHandler.class);
	private NameCallback nameCallback;
	private PasswordCallback passwordCallback;
	private String user;
	private String passwd;

	/**
	 * Initialize username and password
	 * 
	 * @param user
	 * @param passwd
	 */
	protected JAASCallbackHandler(String user, String passwd) {
		this.user = user;
		this.passwd = passwd;
	}

	/**
	 * fetches the username
	 * 
	 * @return
	 */
	public String getUser() {
		return user;
	}

	/**
	 * Fetches the password
	 * 
	 * @return
	 */
	public String getPasswd() {
		return passwd;
	}

	/*
	 * Custom CallbackHandler
	 * 
	 * @see
	 * javax.security.auth.callback.CallbackHandler#handle(javax.security.auth
	 * .callback.Callback[])
	 */
	public void handle(Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {

		// Check for callbacks user and password
		for (Callback callback : callbacks) {
			if (callback instanceof NameCallback) {
				nameCallback = (NameCallback) callback;
				nameCallback.setName(this.user);
				LOG.info("NameCallBack : " + nameCallback);
			} else if (callback instanceof PasswordCallback) {
				passwordCallback = (PasswordCallback) callback;
				passwordCallback.setPassword(this.passwd.toCharArray());
				LOG.info("PasswordCallBack : " + passwordCallback);
			}
		} // End of for ()
	} // End of method
} // End of class
